/*================================================================
*   文件名称：main.cpp
*   创 建 者：yang qiang
*   创建日期：2019年05月26日
*   描    述：
*   Copyright (C) 2019 All rights reserved.
*   
================================================================*/


#include <iostream>

using namespace std;

const int branchnum = 26;

struct TrieNode{
    bool isend;
    TrieNode *next[branchnum];
};

class Trie {
public:
    TrieNode *root = new TrieNode();
    /** Initialize your data structure here. */
    Trie() {
        root->isend = false;
        for(int i = 0; i < branchnum; i++){
            root->next[i] = NULL;
        }
    }
    
    /** Inserts a word into the trie. */
    void insert(string word) {
        int size = word.size();
        if( size == 0 )
            return;
        
        char c;
        int i = 0;
        TrieNode* p = root;

        while( i < size ){
            c = word[i];
            if( p->next[c - 'a'] == NULL ){
                p->next[c - 'a'] = new TrieNode();
                p = p->next[c - 'a'];
                p->isend = false;
                for(int j = 0; j < branchnum; j++){
                    p->next[j] = NULL;
                }
            }else{
                p = p->next[c - 'a'];
            }

            i++;
        }
        
        p->isend = true;
    }
    
    /** Returns if the word is in the trie. */
    bool search(string word) {
        int size = word.size();
        if( size == 0 )
            return false;

        char c;
        TrieNode *p = root;
        for(int i = 0; i < size; i++){
            c = word[i];
            if( p->next[c - 'a'] == NULL ){
                return false;
            }
            p = p->next[c - 'a'];
        }

        return p->isend;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    bool startsWith(string prefix) {
        int size = prefix.size();
        if( size == 0 )
            return false;

        char c;
        TrieNode* p = root;
        for(int i = 0; i < size; i++){
            c = prefix[i];
            if(p->next[c - 'a'] == NULL){
                return false;
            }
            
            p = p->next[c - 'a'];
        }

        return true;
    }

};

/**
 * Your Trie object will be instantiated and called as such:
 * Trie* obj = new Trie();
 * obj->insert(word);
 * bool param_2 = obj->search(word);
 * bool param_3 = obj->startsWith(prefix);
 */
